package com.my.dao.impl;

import java.math.BigInteger;
import java.util.List;

import com.my.bean.Address;
import com.my.dao.AddressDAO;
import com.my.dao.IBaseDAO;

public class AddressDAOImpl implements AddressDAO {
	private IBaseDAO<Address> basedao;

	public void setBasedao(IBaseDAO<Address> basedao) {
		this.basedao = basedao;
	}

	@Override
	public boolean addAddress(Address address) throws Exception {
		if (this.checkAddress(address)) {
			return basedao.add(address);
		}
		return false;
	}

	@Override
	public boolean editAddress(Address address) throws Exception {
		if (this.checkAddress(address)) {
			return basedao.edit(address);
		}
		return false;
	}

	@Override
	public Address getAddressById(Class<Address> c, Integer id)
			throws Exception {
		return basedao.getById(c, id);
	}

	@Override
	public boolean removeAddress(Integer id) throws Exception {
		Address address = basedao.getById(Address.class, id);
		if (address != null) {
			basedao.remove(address);
		}
		return false;
	}

	@Override
	public BigInteger getTotalAddressRecords() throws Exception {
		String sql = "select count(address_id) from info_address";
		return basedao.getTotalRecords(sql);
	}

	@Override
	public List<Address> getAllAddressByPage(int pageindex, int pagesize)
			throws Exception {
		String hql = "from Address";
		return basedao.getAllEntityByPage(hql, pageindex, pagesize);
	}

	@Override
	public BigInteger searchTotalAddressRecords(Address address)
			throws Exception {
		String sql = "select count(address_id) from info_address where province like ? and city like ?";
		String item1 = address.getProvince() + "%";
		String item2 = address.getCity() + "%";
		return basedao.getTotalRecords(sql, item1, item2);
	}

	@Override
	public List<Address> searchAddressByPage(int pageindex, int pagesize,
			Address address) throws Exception {
		String hql = "from Address as a where a.province like ? and a.city like ?";
		String item1 = address.getProvince() + "%";
		String item2 = address.getCity() + "%";
		return basedao.getAllEntityByPage(hql, pageindex, pagesize, item1,
				item2);
	}

	boolean checkAddress(Address address) {
		if (address == null || address.getName() == null
				|| address.getName().isEmpty()) {
			return false;
		} else {
			return true;
		}
	}

	@Override
	public boolean isExist(String name) {
		if (name.isEmpty()) {
			return false;
		}
		String hql = "from Address as a where a.name=?";
		return basedao.isExist(hql, name);
	}

}
